import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Button, TreeSelect } from 'antd';

import ShowMoreModal from './ShowMoreModal';

const TreeSelector = ({ id, value, onChange, coverage, rate, p_date }) => {
  const [treeData, setTreeData] = useState([]);
  const [show, setShow] = useState(false);
  const [changeValue, setChangeValue] = useState([]);
  const { SHOW_PARENT } = TreeSelect;
  const dispatch = useDispatch();

  const treeCallback = useCallback((data) => {
    return data.map((item) => {
      if (item.children) {
        return {
          children: treeCallback(item.children),
          title: item.value,
          value: item.value,
          key: item.tagDataId,
        };
      }
      return {
        title: item.value,
        value: item.value,
        key: item.tagDataId,
      };
    });
  }, []);

  useEffect(() => {
    dispatch({
      type: 'label/loadTagTree',
      payload: {
        tagId: id,
        callback: (data) => {
          setTreeData(treeCallback(data));
        },
      },
    });
  }, [id, dispatch, treeCallback]);

  const change = (_value, _, extra) => {
    if (!extra) return;
    const isChecked = extra.checked;
    const valueArr = extra.allCheckedNodes.map((ele) => ({
      tagDataId: isChecked ? Number(ele.node.key) : Number(ele.key),
      value: isChecked ? ele.node.props?.value : ele.props?.value,
    }));
    setChangeValue(valueArr);
    onChange(valueArr);
  };

  const handleDelete = (tagValue) => {
    const valueArr = changeValue.filter((item) => item.value !== tagValue);
    setChangeValue(valueArr);
    onChange(valueArr);
  };

  const tProps = {
    treeData,
    value,
    onChange: change,
    treeCheckable: true,
    showCheckedStrategy: SHOW_PARENT,
    placeholder: 'Please select',
    maxTagCount: 10,
    style: {
      width: '100%',
    },
  };
  return (
    <>
      <TreeSelect {...tProps} />
      <Button
        type="link"
        style={{ paddingLeft: 0 }}
        onClick={() => setShow(true)}
        disabled={!value || value.length === 0}
      >
        查看全部
      </Button>
      <ShowMoreModal
        showModal={show}
        setShowModal={setShow}
        value={value}
        coverage={coverage}
        rate={rate}
        p_date={p_date}
        handleDeleteTag={handleDelete}
      />
    </>
  );
};

export default TreeSelector;
